package cn.wenhe9.yygh.user.service.impl;

import cn.wenhe9.yygh.cmn.client.DictFeignClient;
import cn.wenhe9.yygh.common.exception.YyghException;
import cn.wenhe9.yygh.common.helper.JwtHelper;
import cn.wenhe9.yygh.common.result.ResultCodeEnum;
import cn.wenhe9.yygh.common.result.ResultResponse;
import cn.wenhe9.yygh.enums.AuthStatusEnum;
import cn.wenhe9.yygh.enums.DictEnum;
import cn.wenhe9.yygh.model.user.UserInfo;
import cn.wenhe9.yygh.model.vo.user.LoginVo;
import cn.wenhe9.yygh.model.vo.user.UserAuthVo;
import cn.wenhe9.yygh.model.vo.user.UserInfoQueryVo;
import cn.wenhe9.yygh.user.mapper.UserInfoMapper;
import cn.wenhe9.yygh.user.service.PatientService;
import cn.wenhe9.yygh.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author DuJinliang
 * 2022/4/4
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private PatientService patientService;

    @Resource
    private DictFeignClient dictFeignClient;

    @Override
    public ResultResponse loginUser(LoginVo loginVo) {
        //从loginVo获取输入的手机号 和 验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        //判断手机验证码和输入的验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //绑定手机号
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(loginVo.getOpenid())){
            userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
            if (null != userInfo){
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            }else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }

        //如果userInfo为空，进行正常的手机登录
        if (userInfo == null){
            //判断是否是第一次登录 根据手机号查询数据库 如果不存在相同手机号就是第一次登录
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(queryWrapper);

            if (userInfo == null){
                //第一次使用这个手机号进行登录
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        if (userInfo.getStatus() == 0){
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //不是第一次 直接登录
        //返回登录用户名
        //返回token信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //使用jwt生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return ResultResponse.ok(map);
    }

    @Override
    public ResultResponse userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);

        //设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        //进行信息更新
        baseMapper.updateById(userInfo);

        return ResultResponse.ok();
    }

    @Override
    public ResultResponse findUserInfoByPage(Long page, Long limit, UserInfoQueryVo userInfoQueryVo) {
        Page<UserInfo> pageParam = new Page<>(page, limit);
        //UserInfoQueryVo获取条件值
        //用户名称
        String name = userInfoQueryVo.getKeyword();
        //用户状态
        Integer status = userInfoQueryVo.getStatus();
        //认证状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        //开始时间
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        //结束时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return ResultResponse.ok(pages);
    }

    @Override
    public ResultResponse lockUser(Long userId, Integer status) {
        if (status == 0 || status == 1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            int flag = baseMapper.updateById(userInfo);
            if (flag > 0){
                return ResultResponse.ok();
            }
            return ResultResponse.fail();
        }
        return ResultResponse.fail(ResultCodeEnum.PARAM_ERROR);
    }

    @Override
    public ResultResponse getUserDetailById(Long userId) {
        Map<String, Object> map = new HashMap<>();
        //根据userId查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo", userInfo);
        //根据userId查询就诊人信息
        ResultResponse patientResponse = patientService.findAllByUserId(userId);
        map.put("patientList", patientResponse.getData());
        return ResultResponse.ok(map);
    }

    @Override
    public ResultResponse approval(Long userId, Integer authStatus) {
        //2 通过 -1 不通过
        if (authStatus == 2 || authStatus == -1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            int flag = baseMapper.updateById(userInfo);
            if (flag > 0){
                return ResultResponse.ok();
            }
            return ResultResponse.fail();
        }
        return ResultResponse.fail();
    }

    public UserInfo selectWxInfoOpenId(String openid){
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 编号变成对应值封装
     * @param userInfo UserInfo
     * @return UserInfo
     */
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        String certificatesTypeString = dictFeignClient.getName(DictEnum.CERTIFICATES_TYPE.getDictCode(), userInfo.getCertificatesType());
        userInfo.getParam().put("certificatesTypeString", certificatesTypeString);

        return userInfo;
    }
}
